<template>
	<div class="city-list">
		<div
			v-for="(item, index) in cityList"
			:key="index"
			class="item"
			:class="{ active: activeVal.includes(item) && showActive }"
			@click="handleSelect(item, index)"
		>
			{{ item }}
		</div>
	</div>
</template>
<script>
export default {
	props: {
		biz_id: [String, Number],
		value: {
			type: Array,
			default: () => []
		},
		multiple: {
			type: Boolean,
			default: false
		},
		showActive: {
			type: Boolean,
			default: false
		},
		tpl: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			visible: false,
			list: [],
			activeVal: this.value
		};
	},
	computed: {
		cityList() {
			const { city_data } = this.tpl;
			return city_data?.split(",")?.filter(Boolean) || [];
		},
		activeIds() {
			return this.activeVal.map((v) => v.id);
		}
	},
	watch: {
		biz_id() {
			// this.getAdFormCity();
		},
		value(v) {
			this.activeVal = v;
		}
	},
	created() {
		// this.getAdFormCity();
	},
	methods: {
		async getAdFormCity() {
			if (!this.biz_id) return;
			this.list = await this.$api.getAdFormCity({ biz_id: this.biz_id });
		},
		handleSelect(item) {
			this.$emit("select", item);
			if (!this.multiple) {
				this.activeVal = this.activeVal[0] == item ? [] : [item];
				this.handleChange();
				return;
			}
			let currIdx = this.activeIds.findIndex((v) => v == item.id);
			if (currIdx > -1) {
				this.activeVal.splice(currIdx, 1);
			} else {
				this.activeVal.push(item);
			}
			this.handleChange();
		},
		handleChange() {
			this.$emit("input", this.activeVal);
		}
	}
};
</script>
<style lang="scss" scoped>
.city-list {
	display: flex;
	flex-wrap: wrap;
	width: 100%;
	.item {
		background: #fff6ee;
		border: 1px solid #ff7400;
		color: #ff7400;
		text-align: center;
		font-size: 0.3555555rem;
		width: 29%;
		height: 1rem;
		line-height: 1rem;
		// float: left;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		border-radius: 4px;
		margin: 2%;
		padding: 0 0.2rem;
		box-sizing: border-box;
		transition: all 0.2s ease;
		&.active {
			background-color: #ff7400;
			color: #fff;
		}
	}
}
</style>
